from django.db.models import Q
from rest_framework import viewsets
from ERP_system.utils.multiple_destory import MultipleDestoryMixin,MultipleOpenMixin
from ERP_system.utils.pagination import GlobalPagination
from goods_info.models import *
from goods_info.serializer.goods_serializer import GoodsBaseSerializer,GoodsGetSerializer


class GoodsView(viewsets.ModelViewSet,MultipleDestoryMixin,MultipleOpenMixin):

    queryset = GoodsModel.objects.all()

    serializer_class = GoodsBaseSerializer


   # pagination_class = GlobalPagination

    def get_serializer_class(self):
        if self.action=='list' or self.action=='retrieve':
            return GoodsGetSerializer
        else:
            return GoodsBaseSerializer
    def get_queryset(self):
        if self.action == 'list':  # 过滤查询
            # 获取请求参数(在json中)：
            keyword = self.request.data.get('keyword', None)
            color = self.request.data.get('color', None)
            category = self.request.data.get('category', 0)
            number_code = self.request.data.get('number_code', None)
            basic_weight = self.request.data.get('basic_weight', None)
            expiration_day = self.request.data.get('expiration_day', 0)
            delete_flag = self.request.data.get('delete_flag', None)
            query = Q()
            if keyword:
                child_query = Q()
                child_query.add(Q(name__contains=keyword), 'OR')
                child_query.add(Q(specification=keyword), 'OR')
                child_query.add(Q(model_number=keyword), 'OR')
                query.add(child_query, 'AND')
            if color:
                query.add(Q(color=color), 'AND')
            if category:
                query.add(Q(category__id=category), 'AND')
            if number_code:
                query.add(Q(number_code__contains=number_code), 'AND')
            if basic_weight:
                query.add(Q(basic_weight=basic_weight), 'AND')
            if expiration_day:
                query.add(Q(expiration_day=expiration_day), 'AND')
            if delete_flag:
                query.add(Q(delete_flag=delete_flag), 'AND')
            return GoodsModel.objects.filter(query).all()
        else:
            return GoodsModel.objects.all()





